<template>
  <div class="countdown">
    {{ formattedTime }}
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue';

const props = defineProps({
  startTime: String
});

const countdownTime = ref(0);
const formattedTime = ref('');
let interval = null;

// 解析输入的时间字符串
const parseTime = (timeString) => {
  const parts = timeString.split(':').map(Number);
  const minutes = parts[0];
  const seconds = parts[1];
  const milliseconds = parts[2];
  return (minutes * 60 * 1000) + (seconds * 1000) + milliseconds;
};

// 格式化时间显示
const formatTime = (totalMilliseconds) => {
  const minutes = Math.floor(totalMilliseconds / 60000);
  const seconds = Math.floor((totalMilliseconds % 60000) / 1000);
  const milliseconds = totalMilliseconds % 1000;
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}:${milliseconds.toString().padStart(3, '0')}`;
};

// startCountdown 方法
const startCountdown = () => {
  interval = setInterval(() => {
    if (countdownTime.value > 0) {
      countdownTime.value -= 10; // 更新时间间隔为10毫秒，以平衡性能和精度
      formattedTime.value = formatTime(countdownTime.value);
    } else {
      clearInterval(interval);
    }
  }, 10);
};

const pauseCountdown = () => {
  clearInterval(interval);
  interval = null;
};

const resetCountdown = () => {
  pauseCountdown();
  countdownTime.value = parseTime(props.startTime);
  formattedTime.value = formatTime(countdownTime.value);
};


// 组件创建时初始化倒计时显示
onMounted(() => {
  countdownTime.value = parseTime(props.startTime);
  formattedTime.value = formatTime(countdownTime.value);
});


onBeforeUnmount(() => {
  if (interval) {
    clearInterval(interval);
  }
});

// 向外暴露 startCountdown 方法
defineExpose({startCountdown, pauseCountdown, resetCountdown});
</script>

<style lang="scss">
@import "@/assets/base";

.countdown {
  font-size: 150px;
  color: $theme-color;
}
</style>
